/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cl.tienda.control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.entity.Carrito;
import models.entity.Producto;
import models.entity.Usuario;

/**
 *
 * @author 18205719-3
 */
public class Carrito3 extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Carrito3</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Carrito3 at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        
        HttpSession sesion=request.getSession();
        Vector<Carrito> carritoCompra=null;
        Vector<Producto> productos=(Vector<Producto>)sesion.getAttribute("productos");
        Usuario usuario=(Usuario)sesion.getAttribute("usuarioInicio");
        //Si se creo la sesion con el atributo de carrito
        if(sesion.getAttribute("carrito")!=null){
        //Si existe una sesion con ese atributo, se obtiene los datos de esa sesion
            carritoCompra=(Vector<Carrito>)sesion.getAttribute("carrito");
        }else{
        //Si no existe esa sesion se crea el carrito de compras
        carritoCompra=new Vector<Carrito>();
            }
        //Obtenemos los valores de la cajas de texto
        int indice=Integer.parseInt(request.getParameter("txtIndice").trim());
        int cantidad=Integer.parseInt(request.getParameter("txtCantidad").trim());
        float subTotal=cantidad * productos.get(indice).getPrecio();
        //Creo el elemento carrito
        Carrito car=new Carrito();
        car.setCodigo(indice);
        car.setProducto(productos.get(indice));
        car.setUsuario(usuario);
        car.setCantidadPedida(cantidad);
        car.setSubTotal(subTotal);
        //Agrego el carrito a mi vector
        carritoCompra.add(car);
        sesion.setAttribute("carrito",carritoCompra);
        PrintWriter out=response.getWriter();
        mostrarPagina(out, carritoCompra);
        out.close();    
    }
    
     public void mostrarPagina(PrintWriter out, Vector<Carrito> carritoCompras){
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Consultar Producto</title>");      
        out.println("</head>");
        out.println("<body>");
        out.println("<table border='2' align='center'>");
        out.println("<tr>");
        out.println("<th><a href='mostrarproductos.jsp'>Consultar Productos</a> | <a href='agregarcarrito1.jsp'>Agregar al Carrito</a> | <a href='login.html'>Salir</a></th>");
        out.println("</tr>");
        out.println("</table>");
        
        out.println("<table>");
        out.println("<tr>");
        out.println("<td width='68%'><h4>Nombre</h4></td>");
        out.println("<td width='16%' align='right' valign='top'><h4>Stock</span></h4></td>");
        out.println("<td width='16%' align='right' valign='top'><h4>Precio</span></h4></td>");
        out.println("</tr>");

        //Vamos a mostrar la lista de productos del vector de Productos

        for(int i=0; i<carritoCompras.size(); i++){
            
            out.println("<tr>");
            out.println("<td>" + carritoCompras.get(i).getProducto().getNombre()+ "</td>");
            out.println("<td align='right' valign='top'>"+ carritoCompras.get(i).getCantidadPedida() +"</td>");
            out.println("<td align='right' valign='top'>"+ carritoCompras.get(i).getSubTotal() +"</td>");
            out.println("</tr>");
        }

        out.println("</table></td>");
        out.println("</tr>");
        out.println("<tr>");
        out.println("<td colspan=\"2\" aling=\"center\"><a href=\"cfinalizarcompra.do\">FINALIZAR COMPRA</a></td>");
        out.println("</tr>");
        out.println("</table>");
        out.println("</body>");
        out.println("</html>");

        out.close();
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
